<template>
  <div class="app-container">
    <el-container>
      <el-header style="height: auto;">
        <el-select
          v-model="source"
          placeholder="来源"
          :remote-method="handleGetDataSource"
          :loading="datasource_loading"
          remote
          filterable
          clearable
          style="width: 250px"
        >
          <el-option
            v-for="item in data_sources"
            :key="item.id"
            :label="item.source"
            :value="item.source"
          />
        </el-select>
        <el-select v-model="crawl_count" placeholder="类型" clearable style="width: 150px">
          <el-option label="爬取完毕" value="100" />
          <el-option label="可用产品" value="200" />
          <el-option label="垃圾产品" value="300" />
          <el-option label="已使用" value="600" />
          <el-option label="所有" value="0" />
        </el-select>
        <el-input v-model="kwInput" placeholder="输入任意字符 进行筛选" clearable class="input-with-select" style="width: 60%">
          <el-select slot="prepend" v-model="platform" placeholder="platform" filterable size="mini" clearable style="width: 200px">
            <el-option
              v-for="item in platforms"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-button slot="append" type="primary" icon="el-icon-search" :loading="listLoading" @click="getList">搜索</el-button>
        </el-input>
        <el-button
          type="success"
          class="el-icon-plus"
          :disabled="listLoading"
          @click="handleAction('create', '添加竞品分析')"
        >添加分析
        </el-button>
      </el-header>
      <el-container>
        <el-main>
          <el-table
            v-loading="listLoading"
            :data="data"
            border
            fit
            highlight-current-row
            :default-sort="{prop: 'create_at', order: 'descending'}"
            style="width: 100%"
            @cell-mouse-enter="(m) => m.active=true"
            @cell-mouse-leave="(m) => m.active=false"
            @sort-change="handleSort"
            @selection-change="handleSelectionChange"
          >
            <el-table-column
              type="selection"
              width="55"
            />
            <el-table-column label="image" prop="image">
              <template slot-scope="scope">
                <a :href="scope.row.url" target="_blank"><img :src="scope.row.image" style="height: auto;width: 220px"></a>
                <span style="display: block">{{ scope.row.price }}</span>
                <span style="display: block">{{ scope.row.source }}</span>
                <el-button type="primary" size="mini" @click="handleAddCrawlUrl(scope.row)">添加爬取</el-button>
              </template>
            </el-table-column>
            <el-table-column label="信息摘要" prop="price" sortable="custom">
              <template slot-scope="scope">
                <span style="display: block">{{ scope.row.keyword }}</span>
                <span style="display: block">价格:{{ scope.row.price }}</span>
                <span style="display: block">订单:{{ scope.row.orders }}</span>
                <span>均价:<span style="color: red">{{ scope.row.average_price }}</span></span><span>总数:{{ scope.row.products_count }}</span>
                <span style="display: block">高于2x:{{ scope.row.price_list.filter(m => m >= scope.row.price*2).length }}个</span>
                <span style="display: block">低于采购:{{ scope.row.price_list.filter(m => m <= scope.row.price).length }}个</span>
              </template>
            </el-table-column>
            <el-table-column label="cpc" prop="cpc" sortable="custom" />
            <el-table-column label="volume" prop="volume" sortable="custom" />
            <el-table-column label="orders" prop="orders" sortable="custom" />
            <el-table-column align="center" label="操作" width="240" fixed="right">
              <template slot-scope="scope">
                <el-button
                  v-show="!scope.row.edit"
                  size="mini"
                  icon="el-icon-eye"
                  type="success"
                  plain
                  @click="handleShowPCP(scope.row)"
                >查看
                </el-button>
                <el-button
                  v-show="!scope.row.edit"
                  size="mini"
                  icon="el-icon-delete"
                  type="danger"
                  plain
                  @click="handleAction('delete', scope.row)"
                >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button v-if="crawl_url_temp.urls.length" size="mini" type="success" style="float: left;margin-top: 5px;" @click="handleMultilCrawlUrl">批量爬取</el-button>
          <el-pagination
            v-if="data.length"
            background
            class="mt-pagination"
            :current-page="page"
            :page-sizes="[10,20,50,100]"
            :page-size="pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
          />
        </el-main>
      </el-container>
    </el-container>
    <el-dialog
      append-to-body
      title="添加新的产品URL"
      :visible.sync="newCrawlURLDialogVisible"
      :close-on-click-modal="false"
    >
      <el-form :model="crawl_url_temp" label-position="left" label-width="160px">
        <el-form-item label="网址">
          <el-input
            v-model="crawl_url_temp.urls"
            type="textarea"
            :autosize="{ minRows: 8}"
            placeholder="输入URL,每行一个"
          />
        </el-form-item>
        <el-form-item label="Tag">
          <el-input v-model="crawl_url_temp.tag" />
        </el-form-item>
        <el-form-item label="ship_from">
          <el-input v-model="crawl_url_temp.ship_from" placeholder="发货地:US/CN" />
        </el-form-item>
        <el-form-item label="来源网站">
          <el-select v-model="crawl_url_temp.web_id" tyle="width: 100%" filterable clearable placeholder="来源网站">
            <el-option v-for="item in this.dataWebs" :key="item.id" :label="item.domain" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="newCrawlURLDialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="modifyloading" @click="handlePostNewCrawlUrl">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      append-to-body
      :title="title"
      :visible.sync="innerDialogVisible"
      :close-on-click-modal="false"
    >
      <el-form :model="temp" label-position="left" label-width="80px">

        <el-form-item label="keyword">
          <el-input v-model="temp.keyword" />
        </el-form-item>
        <el-form-item label="url">
          <el-input v-model="temp.url" />
        </el-form-item>
        <el-form-item label="cpc">
          <el-input v-model="temp.cpc" />
        </el-form-item>
        <el-form-item label="volume">
          <el-input v-model="temp.volume" />
        </el-form-item>
        <el-form-item label="image">
          <el-input v-model="temp.image" />
        </el-form-item>
        <el-form-item label="成本价">
          <el-input v-model="temp.price" />
        </el-form-item>

        <el-form-item label="platfrom">
          <el-select v-model="temp.platform" placeholder="platform" filterable size="mini" clearable>
            <el-option
              v-for="item in platforms"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="innerDialogVisible = false">取 消</el-button>
        <el-button :type="action !== 'delete'?'primary':'danger'" @click="confirm">确 定</el-button>
      </span>
    </el-dialog>
    <platformcompetitiveproduct
      :id="id_platformcompetitiveproduct"
      :is-visible="isVisible_platformcompetitiveproduct"
      :keyword="keyword_platformcompetitiveproduct"
      :image="image_platformcompetitiveproduct"
      :price="price_platformcompetitiveproduct"
      :source="source"
      @closeMyDialog="isVisible_platformcompetitiveproduct=false"
    />
  </div>
</template>

<script>
import { Get, Post, Put, Delete } from '@/api/erp/platformcompetitiveproduct'
import { Get as GetDataSource } from '@/api/erp/platformcpsource'
import { Post as PostCrawlUrl } from '@/api/erp/crawl/crawlurl'
import { GetWebs } from '@/api/erp/crawlproduct'
import qs from 'qs'
import Platformcompetitiveproduct from './elements/platformcompetitiveproduct'

const orderMapper = {
  'ascending': 0,
  'descending': 1,
  'null': ''
}

export default {
  components: { Platformcompetitiveproduct },
  data() {
    return {
      current_item: {},
      modifyloading: false,
      newCrawlURLDialogVisible: false,
      crawl_url_temp: {
        web_id: 19,
        urls: '',
        ship_from: '',
        tag: ''
      },
      dataWebs: [],
      isVisible_platformcompetitiveproduct: false,
      keyword_platformcompetitiveproduct: '',
      price_platformcompetitiveproduct: 0,
      image_platformcompetitiveproduct: '',
      id_platformcompetitiveproduct: '',
      action: '',
      dialogVisible: false,
      innerDialogVisible: false,
      title: '添加关键词',
      temp: {
        is_seed: true,
        keyword: '',
        price: 0,
        image: '',
        url: '',
        cpc: 0,
        volume: 0,
        platform: 'https://shopping.google.com'
      },
      kwInput: '',
      dk: '',
      data_sources: [],
      datasource_loading: false,
      source: '',
      crawl_count: '100',
      platform: 'https://shopping.google.com',
      platforms: [
        {
          'label': 'google shopping',
          'value': 'https://shopping.google.com'
        },
        {
          'label': 'Amazon',
          'value': 'https://www.amazon.com'
        }
      ],
      data: [],
      listLoading: false,
      // pagination
      pagesize: 10,
      page: 1,
      total: 0
    }
  },
  created() {
    GetWebs().then((response) => {
      this.dataWebs = response.data
    }).catch(error => {
      console.log(error)
    })
  },
  methods: {
    handleShowPCP(row) {
      this.keyword_platformcompetitiveproduct = row.keyword
      this.image_platformcompetitiveproduct = row.image
      this.id_platformcompetitiveproduct = row.id
      this.price_platformcompetitiveproduct = row.price
      this.isVisible_platformcompetitiveproduct = true
    },
    handlePostNewCrawlUrl() {
      this.modifyloading = true
      PostCrawlUrl(this.crawl_url_temp).then((response) => {
        this.crawl_url_temp.id = ''
        this.crawl_url_temp.urls = ''
        this.modifyloading = false
        this.newCrawlURLDialogVisible = false
        this.handleSetCrawlCount(this.current_item, 600)
        this.getList()
      }).catch(() => {
        this.notify('抓取失败')
        this.modifyloading = false
      })
    },
    handleSetCrawlCount(item, crawl_count) {
      Put(item.id, {
        crawl_count: crawl_count
      }).then((response) => {
        item.crawl_count = crawl_count
        this.$message.success('修改成功')
      })
    },
    handleAddCrawlUrl(item) {
      this.crawl_url_temp.urls = item.url
      this.current_item = item
      this.newCrawlURLDialogVisible = true
    },
    handleMultilCrawlUrl() {
      this.newCrawlURLDialogVisible = true
    },
    handleSelectionChange(rows) {
      const urls = []
      for (let i = 0; i < rows.length; i++) {
        if (rows[i].url.length) {
          urls.push(rows[i].url)
        }
      }
      this.crawl_url_temp.urls = urls.join('\n')
    },
    handleAction(action, row) {
      this.action = action
      switch (action) {
        case 'create':
          this.innerDialogVisible = true
          this.temp = {
            is_seed: true,
            keyword: '',
            image: '',
            price: 0,
            url: '',
            cpc: 0,
            volume: 0,
            platform: 'https://shopping.google.com'
          }
          this.title = row
          break
        case 'delete':
          this.innerDialogVisible = true
          this.title = `确认要删除${row.keyword}?`
          this.temp = row
          break
      }
    },
    confirm() {
      const _data = this.temp
      switch (this.action) {
        case 'create':
          Post(_data).then(response => {
            this.innerDialogVisible = false
            this.getList()
            this.notify('添加成功')
          })
          return
        case 'edit':
          Put(_data.id, _data).then(response => {
            this.innerDialogVisible = false
            this.getList()
            this.notify('更新成功')
          })
          return
        case 'delete':
          Delete(_data.id).then((response) => {
            this.innerDialogVisible = false
            this.getList()
            this.notify('删除成功')
          })
          return
      }
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    handleGetDataSource(query) {
      this.datasource_loading = true
      GetDataSource(null, qs.stringify({
        kw: query,
        pagesize: this.pagesize,
        page: this.page
      }))
        .then(response => {
          this.data_sources = response.data.data
          this.datasource_loading = false
          this.total = response.data.total
        }).catch(e => {
          this.datasource_loading = false
        })
    },
    getList() {
      this.listLoading = true
      Get(null, qs.stringify({
        kw: this.kwInput,
        platform: this.platform,
        pagesize: this.pagesize,
        page: this.page,
        source: this.source,
        order_by: this.order_by,
        order_desc: this.order_desc,
        is_seed: true,
        crawl_count: this.crawl_count
      }))
        .then(response => {
          this.data = response.data.data.map(m => {
            this.$set(m, 'active', false)
            return m
          })
          this.listLoading = false
          this.total = response.data.total
        }).catch(e => {
          this.listLoading = false
        })
    },
    // pageSize 改变后触发 table 更新
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.getList()
    },

    // 点击搜索
    handleSearch() {
      this.page = 1
      this.getList()
    },
    handleSort(v) {
      this.order_by = v.prop
      this.order_desc = orderMapper[v.order]
      this.getList()
    },
    scrollTop() {
      window.scrollTo(0, 0)
    }
  }
}
</script>

<style scoped>

.el-header, .el-footer {
  background-color: #fff;
  color: #333;
  text-align: left;
}

.el-aside {
  background-color: #fff;
  border-left: 1px solid #ebeef5;
  color: #333;
  padding-top: 20px;
  padding-left: 10px;
  line-height: 250px;
}

.el-main {
  background-color: #fff;
  color: #333;
  text-align: center;
}

body > .el-container {
  margin-bottom: 40px;
}

.el-container:nth-child(5) .el-aside,
.el-container:nth-child(6) .el-aside {
  line-height: 260px;
}

.el-container:nth-child(7) .el-aside {
  line-height: 320px;
}

.el-tag + .el-tag {
  margin-left: 10px;
}

/*.top {*/
/*padding-left: 20px;*/
/*padding-right: 20px;*/
/*margin-bottom: 5px;*/
/*margin-top: 28px;*/
/*}*/

/*.head {*/
/*width: calc(20% - 70px);*/
/*}*/

/*.web {*/
/*margin-top: 10px;*/
/*margin-bottom: 10px;*/
/*display: inline-block;*/
/*width: 100%;*/
/*}*/

.web >>> .el-input {
  min-width: 1200px;
}

.app-container >>> .el-dialog {
  margin-top: 48px !important;
  margin-bottom: 68px;
}

.mt-detail:hover, .svg-icon:hover {
  cursor: pointer;
}

.mt-detail {
  color: #1976d2;
}

.mt-dialog >>> .el-dialog {
  margin: 88px auto !important;
}

.clearfix ::after {
  content: "";
  clear: both
}

.mt-table {
  color: black;
  padding: 20px;
}

.mt-pagination {
  float: right;
  margin-top: 10px;
}

.mt-top {
  margin: 15px 0;
}

.mt-row-btn {
  float: right;
  vertical-align: middle;
  color: white;
}

.mt-btn {
  background-color: rgba(0, 0, 0, 0);
  background-image: none;
  border-radius: 1000px;
  border-bottom-style: solid;
  border-bottom-width: 1px;
  border-collapse: collapse;
  border-image-outset: 0px;
  border-image-repeat: stretch;
  border-image-slice: 100%;
  border-image-source: none;
  border-image-width: 1;
  border-left-style: solid;
  border-left-width: 1px;
  border-right-style: solid;
  border-right-width: 1px;
  border-top-style: solid;
  border-top-width: 1px;
  box-sizing: border-box;
  color: #46be8a;
  cursor: pointer;
  display: block;
  float: right;
  font-family: "Helvetica Neue", Helvetica, Tahoma, Arial, "Microsoft Yahei", "Hiragino Sans GB", "WenQuanYi Micro Hei", sans-serif;
  font-size: 14px;
  font-weight: 400;
  height: 26px;
  hyphens: manual;
  line-height: 14px;
  margin-bottom: 0px;
  margin-right: 10px;
  padding: 5px;
  text-align: center;
  text-decoration-color: rgb(82, 96, 105);
  text-decoration-line: none;
  text-decoration-style: solid;
  text-rendering: optimizeLegibility;
  text-size-adjust: 100%;
  touch-action: manipulation;
  transition-delay: 0s, 0s, 0s, 0s;
  transition-duration: 0.2s, 0.2s, 0.2s, 0.2s;
  transition-property: border, color, width, background-color;
  transition-timing-function: linear, linear, linear, linear;
  user-select: none;
  vertical-align: middle;
  visibility: visible;
  white-space: nowrap;
  background: white;
}

.mt-btn:hover + >>> .mt-icon {
  color: #fff;
}

.mt-btn:hover {
  background: #46be8a;
}

.danger:hover {
  background-color: #F56C6C;
}

.danger {
  color: #F56C6C;
}

.default:hover {
  background-color: #62a8ea;
}

.default {
  color: #62a8ea;
}

.edit:hover {
  background-color: #909399;
}

.edit {
  color: #909399;
}

.mt-row-title {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  width: calc(100% - 220px);
  display: inline-block;
  vertical-align: middle;
}

.mt-row-btns {
  float: right;
  margin-right: 10px;
  z-index: 10000;
}

</style>
